package lhc.alg.top100;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * description: https://leetcode.cn/problems/simplify-path/
 *  简化路径 栈
 * author: hongchen.liao
 * date:  2022/9/3
 */
public class _71_Simplify_Path {

    class Solution {
        public String simplifyPath(String path) {
            String[] names = path.split("/");
            Deque<String> stack = new ArrayDeque<>();
            for(String name : names){
                if("..".equals(name)){
                    if(!stack.isEmpty()){
                        stack.pollLast();
                    }
                }else if(name.length() > 0 && !".".equals(name)){
                    stack.offerLast(name);
                }
            }
            StringBuffer ans = new StringBuffer();
            if(stack.isEmpty()){
                ans.append('/');
            }else{
                while(!stack.isEmpty()){
                    ans.append('/');
                    ans.append(stack.pollFirst());
                }
            }
            return ans.toString();
        }
    }


}
